import { proxy } from "valtio";
import { defaultSettings, storage } from "@/store/storage";
import { type NavLinkItem, type SearchEngine, type Settings } from "@/types";

interface CoreState {
  settings: Settings;
  setSettings: (val: Settings, saveToFile: boolean) => void;
  setSearchEngine: (val: SearchEngine) => void;
  setBackground: (val: string) => void;
  setNavLinks: (val: NavLinkItem[]) => void;
}

export const coreState = proxy<CoreState>({
  settings: defaultSettings,
  setSettings(val: Settings, saveToFile: boolean) {
    this.settings = val;
    if (saveToFile) setStorage(val);
  },
  setSearchEngine(val: SearchEngine) {
    this.settings.searchEngine = val;
    setStorage(this.settings);
  },
  setBackground(val: string) {
    this.settings.background = val;
    setStorage(this.settings);
  },
  setNavLinks(val: NavLinkItem[]) {
    this.settings.navLinks = val;
    setStorage(this.settings);
  },
});

function setStorage(st: Settings) {
  storage.set(JSON.stringify(st));
}
